<!--
 * @Author: Aaron Huang
 * @Date: 2021-11-27 11:49:17
 * @LastEditors: Aaron
 * @LastEditTime: 2022-03-30 15:35:11
 * @Description: file content
 * @company: 沃尔玛
-->
<template>
  <div v-loading="assignmentParams.loading" class="schedule-list">
    <search-head :search-data="searchData" :type="assignmentParams.type" @search="search" @reset="reset" @download="download" />
    <assignment
      v-show="assignmentParams.type === scheduleListID.processingTasks"
      :ref="scheduleListID.processingTasks"
      :type="scheduleListID.processingTasks"
      :assignment-params="assignmentParams"
      @operationLog="operationLog"
      @examine="examine"
      @selectionCriteria="selectionCriteria"
      @chooseType="chooseType"
      @entrustInfo="entrustInfo"
      @submitInfo="submitInfo"
      @submitReview="submitReview"
      @make="make"
    >
      <div slot="right" class="mb-8">
        <b>批量操作：</b>
        <el-button-group>
          <el-button
            :disabled="btnDisabled[assignmentParams.type] ? btnDisabled[assignmentParams.type].batchChooseCriteria : true"
            size="mini"
            type="primary"
            class="ml5"
            round
            @click="batchChooseCriteria"
          >
            选择建品标准
          </el-button>

          <el-button
            :disabled="btnDisabled[assignmentParams.type] ? btnDisabled[assignmentParams.type].batchChooseType : true"
            size="mini"
            type="primary"
            class="ml5"
            round
            @click="batchChooseType"
          >
            选择建品方式
          </el-button>

          <el-button
            :disabled="btnDisabled[assignmentParams.type] ? btnDisabled[assignmentParams.type].batchEntrustInfo : true"
            size="mini"
            type="primary"
            class="ml5"
            round
            @click="batchEntrustInfo"
          >
            补充委托信息
          </el-button>

          <el-button
            :disabled="btnDisabled[assignmentParams.type] ? btnDisabled[assignmentParams.type].batchEntrustInfo : true"
            size="mini"
            type="primary"
            class="ml5"
            round
            @click="batchSubmitInfo"
          >
            提交委托
          </el-button>
          <el-button
            :disabled="btnDisabled[assignmentParams.type] ? btnDisabled[assignmentParams.type].BatchApprove : true"
            size="mini"
            type="primary"
            class="ml5"
            round
            @click="BatchApprove"
          >
            提交审核
          </el-button>
        </el-button-group>
      </div>
    </assignment>
    <assignment
      v-show="assignmentParams.type === scheduleListID.allTasks"
      :ref="scheduleListID.allTasks"
      :type="scheduleListID.allTasks"
      :assignment-params="assignmentParams"
      @operationLog="operationLog"
      @examine="examine"
      @abandoned="abandoned"
    >
      <div slot="right" class="mb-8">
        <b>批量操作：</b>
        <el-button
          :disabled="btnDisabled[assignmentParams.type] ? btnDisabled[assignmentParams.type].abandoned : true"
          size="mini"
          type="danger"
          class="ml5"
          round
          @click="batchAbandoned"
        >
          作 废
        </el-button>
        <el-button
          :disabled="btnDisabled[assignmentParams.type] ? btnDisabled[assignmentParams.type].abandoned : true"
          size="mini"
          type="primary"
          class="ml5"
          round
          @click="batchSign"
        >
          打 标
        </el-button>
      </div>
    </assignment>
    <assignment
      v-show="assignmentParams.type === scheduleListID.historicalTasks"
      :ref="scheduleListID.historicalTasks"
      :type="scheduleListID.historicalTasks"
      :assignment-params="assignmentParams"
    />
    <create-goods-type ref="createGoodsTypeRef" :form-date="formDate" @savaSuccess="savaSuccess" />
    <task-standard ref="taskStandardRef" :form-date="formDate" @savaSuccess="savaSuccess" />
    <operation-log ref="operationLogRef" :process-data-list="processDataList" />
    <sign ref="sign" :sign-form="signForm" @savaSuccess="savaSuccess" />
  </div>
</template>

<script>
/* eslint-disable space-before-function-paren */
import searchHead from '../components/searchHead.vue'
import assignment from '../components/assignment.vue'
import taskStandard from '../components/taskStandard.vue'
import createGoodsType from '../components/createGoodsType.vue'
import sign from '../components/sign.vue'
import operationLog from '@/views/coi/approve/components/operationLog.vue'
import { scheduleListID } from '@/views/coi/commonJs/tableHeadList.js'
import { abandonedTask, processData, getPbSupplier, submit, batchSubmitApproval } from '@/api/coi/onlineTaskAPI/sku'
import bus from '@/utils/eventBus.js'

export default {
  name: 'ScheduleList',
  components: {
    searchHead,
    assignment,
    taskStandard,
    createGoodsType,
    sign,
    operationLog
  },
  data() {
    return {
      scheduleListID,
      assignmentParams: {
        type: scheduleListID.processingTasks,
        loading: false,
        queryNum: 0
      },
      searchData: {},
      btnDisabled: {},
      processDataList: [],
      formDate: {
        data: []
      },
      signForm: {
        skuType: 1,
        idList: []
      }
    }
  },
  created() {
    if (this.$route.params && this.$route.params.type) this.assignmentParams.type = this.$route.params.type
  },
  activated() {
    if (this.$route.params && this.$route.params.type) {
      this.assignmentParams.type = this.$route.params.type
      this.reset()
    }
  },
  mounted() {
    this.$nextTick(function () {
      const tableListId = Object.keys(scheduleListID)
      tableListId.forEach((item) => {
        const value = scheduleListID[item]
        this.btnDisabled[value] = this.$refs[value].btnDisabled
      })
    })
  },
  methods: {
    /**
     * 共性
     */
    search() {
      this.$refs[this.assignmentParams.type].search()
    },
    // 重置检索条件
    reset() {
      this.$refs[this.assignmentParams.type].reset()
    },
    download() {
      this.$refs[this.assignmentParams.type].downloadData()
    },
    // 操作日志
    async operationLog(id) {
      const { result } = await processData(id)
      if (Array.isArray(result) && result.length) {
        this.$refs.operationLogRef.dialogVisible = true
        this.processDataList = result
      } else {
        this.$message({
          type: 'warning',
          message: '未查询到该商品线上建品的操作日志'
        })
      }
    },
    // 校验批量数据
    checkQuantity(val, maNum = 500) {
      const arr = val && Array.isArray(val) ? val : false
      const multipleSelection = arr || this.$refs[this.assignmentParams.type].multipleSelection
      if (multipleSelection.length > maNum) {
        this.$message({
          type: 'warning',
          message: `批量任务数量不能超过${maNum}条`
        })
        return false
      } else return multipleSelection
    },
    savaSuccess() {
      this.$refs[this.assignmentParams.type].search()
    },
    examine({ row }) {
      if (row.mainStatus >= 2000 && row.mainStatus < 4000) this.goDetailPage(row.skuName, `/scheduleList/entrustInformation/review/${row.id}`)
      else this.goDetailPage(row.skuName, `/approvalDetails/${row.id}/${row.mainStatus}/${this.$route.name}/${this.$parent.value}`)
    },
    goDetailPage(tagName, path) {
      bus.$emit('setTagName', tagName)
      this.$router.push({
        path
      })
    },
    /**
     * 待我处理列表
     */

    // 请求pb的文描
    async queryPbSupplier(list) {
      const { result } = await getPbSupplier(list)
      return result
    },

    // 选择建品标准
    selectionCriteria({ row }) {
      this.batchChooseCriteria([row])
    },
    batchChooseCriteria(val) {
      const listData = this.checkQuantity(val)
      if (!listData) return
      const list = JSON.parse(JSON.stringify(listData))
      list.forEach((element) => {
        const deptNbr = ('0' + element.deptNbr).slice(-2)
        if (element.buildStandard === 0) element.buildStandard = null // 建品标准默认0.没有时候应该不展示
        if (element.directImportFlag === 1) element.buildVendorNbr = `382575${deptNbr}0`
        else element.buildVendorNbr = ''
      })
      this.formDate.data = list
      this.$refs.taskStandardRef.dialogVisible = true
    },

    // 选择建品方式
    chooseType({ row }) {
      this.batchChooseType([row])
    },
    async batchChooseType(val) {
      const listData = this.checkQuantity(val)
      if (!listData) return
      const data = JSON.parse(JSON.stringify(listData))
      const everyPb = data.every((item) => item.pbVendorFlag || item.directImportFlag)
      const everyUnPb = data.every((item) => !item.pbVendorFlag && !item.directImportFlag)
      if (!everyUnPb) {
        const obj = {}
        const obj2 = {}
        const idList = data
          .filter((item) => item.pbVendorFlag || item.directImportFlag)
          .reduce((item, next) => {
            let flag = true
            obj[next.deptNbr] ? (flag = false) : (obj[next.deptNbr] = true)
            obj2[next.finelineNbr] ? (flag = false) : (obj[next.finelineNbr] = true)
            if (flag) item.push(next)
            return item
          }, [])
          .map((e) => {
            return { deptNbr: e.deptNbr, finelineNbr: e.finelineNbr }
          })
        console.log(idList)
        const pbOptionList = await this.queryPbSupplier(idList)
        data.forEach((item) => {
          if (item.pbVendorFlag || item.directImportFlag) {
            const key = `${item.deptNbr}-${item.finelineNbr}`
            if (pbOptionList && pbOptionList[key] && pbOptionList[key].length) {
              item.pbOption = pbOptionList[key]
              item.contentMerchantId = pbOptionList[key][0].vendorNbr
            } else item.pbOption = []
          }
        })
      }
      this.formDate = { data }
      this.$refs.createGoodsTypeRef.dialogVisible = true
      if (!everyPb) {
        this.$nextTick(() => {
          this.$refs.createGoodsTypeRef && this.$refs.createGoodsTypeRef.querySupplier()
        })
      }
    },
    // 委托信息页面的跳转
    entrustInfo({ row }) {
      this.batchEntrustInfo([row])
    },
    batchEntrustInfo(val) {
      const listData = this.checkQuantity(val, 20)
      if (!listData) return
      const idList = listData.map((_) => _.id).join()
      this.goEntrustInformation(idList)
      this.search()
    },
    goEntrustInformation(idList, type = 'edit') {
      this.$router.push({
        path: `/scheduleList/entrustInformation/${type}/${idList}`
      })
    },
    // 提交委托信息
    submitInfo({ row }) {
      this.batchSubmitInfo([row])
    },
    async batchSubmitInfo(val) {
      const listData = this.checkQuantity(val)
      if (!listData) return
      const idList = listData.map((_) => _.id)
      this.$confirm('提交补充委托信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(
          function () {
            this.batchSubmitInfoRequest(idList)
          }.bind(this)
        )
        .catch((_) => {})
    },
    async batchSubmitInfoRequest(idList) {
      const { result } = await submit(idList)
      if (result) {
        this.search()
        this.$message({
          type: 'success',
          message: '提交委托信息成功！'
        })
      }
    },
    // 跳转到制作页面
    make({ row }) {
      const query = {
        idList: row.id
      }
      this.$router.push({
        path: '/VendoraddInformation_Vendor',
        query
      })
    },
    // 提交审核
    submitReview({ row }) {
      this.BatchApprove([row])
    },
    async BatchApprove(val) {
      const listData = this.checkQuantity(val)
      if (!listData) return
      const idList = listData.map((_) => _.id)
      this.$confirm('提交审核信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(
          function () {
            this.BatchApproveInfoRequest(idList)
          }.bind(this)
        )
        .catch((_) => {})
    },
    async BatchApproveInfoRequest(idList) {
      const { result } = await batchSubmitApproval({ skuIds: idList })
      if (result) {
        this.search()
        this.$message({
          type: 'success',
          message: '提交审核信息成功！'
        })
      }
    },

    /**
     * 所有任务列表
     */
    // 批量作废
    abandoned({ row }) {
      this.batchAbandoned([row])
    },
    batchAbandoned(val) {
      const listData = this.checkQuantity(val)
      if (!listData) return
      const idList = listData.map((_) => _.id)
      this.abandonedRequest(idList)
    },
    // 作废请求
    async abandonedRequest(idList) {
      this.$confirm('此操作将作废建品记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          try {
            console.log(idList)
            const { result } = await abandonedTask(idList)
            if (result) {
              this.$message({
                type: 'success',
                message: result
              })
              this.search()
            }
          } catch (error) {
            console.log(error)
          }
        })
        .catch((_) => {})
    },
    batchSign(val) {
      const listData = this.checkQuantity(val)
      if (!listData) return
      this.signForm.idList = listData.map((_) => _.id)
      this.signForm.skuType = 1
      this.$refs.sign.dialogVisible = true
    }
  }
}
</script>

<style lang="scss" scoped>
.schedule-list {
  height: 100%;
}
.ml5 {
  margin-left: 5px;
}
/deep/ .el-dialog__body {
  padding: 10px 20px;
  overflow: auto;
  max-height: 70vh;
}
.mb-8 {
  margin-bottom: 8px;
}
</style>
